package com.hymjweb.demo.config.filter;

import com.hymjweb.demo.framework.sys.SysConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @BelongsProject: demo1
 * @BelongsPackage: com.hymjweb.demo.config.filter
 * @Author: luoge
 * @CreateTime: 2019-10-16 16:51
 * @Description: 项目的过滤器
 */

public class MyProjectFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(MyProjectFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        HttpServletRequest servletRequest = (HttpServletRequest)request;
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+servletRequest.getContextPath();
        request.setAttribute("base",basePath);
        String jdate = System.currentTimeMillis() + "";
        request.setAttribute("jdate",jdate);

        HttpSession session=servletRequest.getSession();

        if(session!=null && session.getAttribute(SysConstant.SESSION_LOGIN_USER_KEY)!=null){
            chain.doFilter(request,response);
        }
        else{
            ((HttpServletResponse)response).sendRedirect("/login");
            logger.info("请先登录");
        }
    }
}
